//
//  GSAFNetWorkTool.m
//  UITableViewCellPro
//
//  Created by lzhr on 15/9/15.
//  Copyright (c) 2015年 ggs. All rights reserved.
//

#import "GSAFNetWorkTool.h"
#import "AFNetworking.h"
@implementation GSAFNetWorkTool

+ (void)getUrl:(NSString *)url
          body:(id)body
        result:(GSResult)result
    headerFile:(NSDictionary *)headerFile
       success:(void (^)(id result))success
       failure:(void (^)(NSError *error))failure
{
    // 1.获取网络请求管理类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    
    // 2.为网络请求加请求头
    if (headerFile) {
        for (NSString *key in headerFile.allKeys) {
            [manager.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
        }
    }
    // 3.设置返回值类型
    switch (result) {
        case GSData:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case GSJSON:
            break;
        case GSXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
    // 4.设置网络请求返回值所支持的参数类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    
    // 5.发送网络请求
    [manager GET:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            // 成功回调
            [self saveCache:url :responseObject];
            success(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (error) {
            // 失败回调
            NSLog(@"%@",[error description]);
            id loadCach = [self loadCacheData:url];
            failure(loadCach);
        }
    }];
}


+ (void)postUrl:(NSString *)url
           body:(id)body
         result:(GSResult)result
   requestStyle:(GSRequestStyle)requestStyle
     headerFile:(NSDictionary *)headerFile
        success:(void (^)(id result))success
        failure:(void (^)(NSError *error))failure
{
    // 1.获取网络请求管理类
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 2.网络请求请求体Body的类型
    switch (requestStyle) {
        case GSRequestJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case GSRequestString:
            // 返回的body 类型 与 传入的body 类型一致
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, id parameters, NSError *__autoreleasing *error) {
                return parameters;
            }];
            break;
            
        default:
            break;
    }
    
    // 3.为网络请求加请求头
    if (headerFile) {
        for (NSString *key in headerFile.allKeys) {
            [manager.requestSerializer setValue:headerFile[key] forHTTPHeaderField:key];
        }
    }
    // 4.网络请求返回值的数据类型
    switch (result) {
        case GSData:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        case GSJSON:
            break;
        case GSXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    
    // 5.设置网络请求返回值支持的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    
    // 6.发送网络请求
    [manager POST:url parameters:body success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (responseObject) {
            [self saveCache:url :responseObject];
            success(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (error) {
            // 失败回调
            NSLog(@"%@",[error description]);
            id loadCach = [self loadCacheData:url];
            failure(loadCach);
        }
    }];
    
}



//本地缓存
+ (void)saveCache : (NSString *)str : (id)respose
{
    //获取Cach路径
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    //生成fileManager 对象 单例方法
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //拼接路径
    NSString *cacheDirectory = [docPath stringByAppendingPathComponent:@"myCaches"];
    
    //判断 当前路径下是否有 "myCaches" 文件
    if (![fileManager isExecutableFileAtPath:@"myCaches"]) {
        //没有的话 , 创建 文件夹
        [fileManager createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //hash 转码 生成 归档文件名
    NSString *strPath = [NSString stringWithFormat:@"%ld.txt", [str hash]];
    //拼接文件路径
    NSString *path = [cacheDirectory stringByAppendingPathComponent:strPath];
    
    //将文件归档 到Cache 生成的文件夹下
    [NSKeyedArchiver archiveRootObject:respose toFile:path];
    
}
//读取本地缓存
+ (id)loadCacheData : (NSString *)str
{
    //拼接路径
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *cacheDirectory = [docPath stringByAppendingPathComponent:@"myCaches"];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.txt", cacheDirectory, [str hash]];
    //反归档
    id pickData = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    return pickData;
}


@end
